#include "ConfigFile.h"

using namespace std;

ConfigFile::ConfigFile( void ) {}

ConfigFile::~ConfigFile() {}

ConfigSection& ConfigFile::operator[]( std::string section ) throw ( ConfigSectionNotFoundException )
{
    for( unsigned int i = 0; i < m_sections.size(); ++i )
    {
        if( m_sections[ i ].getName() == section )
        {
            return m_sections[ i ];
        }
    }
    throw ConfigSectionNotFoundException( section );
}

bool ConfigFile::load( std::string file ) {
    std::ifstream configFile( file.c_str() );
    if ( configFile ) // ce test échoue si le fichier n'est pas ouvert
    {
        std::string line; // variable contenant chaque ligne lue

        // cette boucle s'arrête dès qu'une erreur de lecture survient
        while ( std::getline( configFile, line ) )
        {
            line = removeFirstSpaces( line );
            if( line[ 0 ] == '#' )
            {
                // Comment
                continue;
            }
            else
            {
                if( line[ 0 ] == '[' )
                {
                    loadSection( line );
                }
                else
                {
                    loadKey( line );
                }
            }
        }
    }
    else
    {
        return false;
    }

    return true;
}

std::string ConfigFile::removeFirstSpaces( std::string str )
{
    std::string temp = str;
    while( str[ 0 ] == ' ' || str[ 0 ] == '\t' )
    {
        str = str.substr( 1, str.size() -1 );
    }
    return str;
}

std::string ConfigFile::removeSpaces( std::string str )
{
    std::string ret = "";
    for( unsigned int i = 0; i < str.size(); ++i )
    {
        if( str[ i ] != ' ' )
        {
            ret += str[i];
        }
    }
    return ret;
}

void ConfigFile::loadKey( std::string line )
{

    std::string name;
    std::string value;
    unsigned int index = line.find("=");
    if( index == string::npos )
    {
        // Skip this key loading
        return;
    }
    name = line.substr( 0, line.size() - ( line.size() - index ) );
    name = removeSpaces( name );
    value = line.substr( index + 1, line.size() - index - 1);
    value = removeSpaces( value );

    ConfigKey key( name, value );
    m_sections[ m_sections.size() - 1 ].addKey( key );
}

void ConfigFile::loadSection( std::string line )
{
    std::string name;
    unsigned int index = line.find("]");
    if( index == string::npos )
    {
        // Skip this section loading
        return;
    }
    name = line.substr( 1, line.size() - ( line.size() - index ) - 1 );
    name = removeSpaces( name );

    ConfigSection section( name );
    m_sections.push_back( section );
}
